package com.zkzx.company.base.service;

import com.zkzx.common.company.model.CompanyDriverVO;
import com.zkzx.common.driver.constants.DriverStatusEnum;
import com.zkzx.common.driver.param.DriverFilterParam;
import com.zkzx.common.driver.vo.DriverStatisticsVO;
import com.zkzx.common.global.Global;
import com.zkzx.common.vo.PageResult;
import com.zkzx.common.vo.RequestFilterParams;
import com.zkzx.company.base.mapper.CompanyDriverMapper;
import com.zkzx.company.base.mapper.CompanyMapper;
import com.zkzx.company.base.mapper.CompanyTruckMapper;
import com.zkzx.company.base.mapper.entity.CompanyDriver;
import com.zkzx.company.base.mapper.entity.CompanyDriverExample;
import com.zkzx.util.sql.SQLUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 北京中科智兴物联科技有限公司 @版权所有
 *
 * @Author: zhaoyihe@zkraising.com
 * @Date: 2021/05/08/17:42
 * @Description:
 */
@Slf4j
@Service
public class CompanyDriverService {

    @Resource
    private CompanyDriverMapper companyDriverMapper;
    @Resource
    private CompanyMapper companyMapper;
    @Resource
    private CompanyTruckMapper companyTruckMapper;


    /**
     * 插入中间表
     * @param companyDriverVO 入参
     */
    public void add( CompanyDriverVO companyDriverVO){
        CompanyDriver companyDriver = new CompanyDriver();
        companyDriver.setCompanyid(companyDriverVO.getCompanyId());
        companyDriver.setDriverid(companyDriverVO.getDriverId());
        companyDriver.setTruckid(companyDriverVO.getTruckId());
        companyDriver.setMobile(companyDriverVO.getMobile());
        companyDriver.setDrivername(companyDriverVO.getDriverName());
        companyDriver.setDriverstatus(companyDriverVO.getDriverStatus());
        companyDriver.setDriversource(companyDriverVO.getDriverSource());
        companyDriver.setLastmodifiedtime(new Date());
        companyDriverMapper.insert(companyDriver);
    }

    /**
     * 查找企业下的所有司机
     * @param filterParam 入参
     * @param params 入参
     */
    public PageResult<CompanyDriverVO> find(DriverFilterParam filterParam, RequestFilterParams params){

        CompanyDriverExample companyDriverExample = new CompanyDriverExample();
        CompanyDriverExample.Criteria criteria = companyDriverExample.createCriteria();
        if (Global.ZERO<filterParam.getCompanyId()){
            criteria.andCompanyidEqualTo(filterParam.getCompanyId());
        }
        if(!StringUtils.isEmpty(filterParam.getName())){
            criteria.andDrivernameLike(SQLUtil.valueBuildLike(filterParam.getName()));
        }
        if(!StringUtils.isEmpty(filterParam.getMobile())){
            criteria.andMobileLike(SQLUtil.valueBuildLike(filterParam.getMobile()));
        }
        if(!StringUtils.isEmpty(filterParam.getStatus())){
            criteria.andDriverstatusEqualTo(filterParam.getStatus());
        }
        if(!StringUtils.isEmpty(filterParam.getSource())){
            criteria.andDriversourceEqualTo(filterParam.getSource());
        }

        long totalNum = companyDriverMapper.countByExample(companyDriverExample);
        if (totalNum <= Global.ZERO){
            return new PageResult<>(params.getPage(),params.getPerPage(), Collections.emptyList(), Global.ZERO);
        }


        companyDriverExample.setOrderByClause(params.getField().concat(" ").concat(params.getOrder()));
        companyDriverExample.page(params.getPage() - Global.ONE , params.getPerPage());

        List<CompanyDriver> companyDriverList = companyDriverMapper.selectByExample(companyDriverExample);
        List<CompanyDriverVO> collect = companyDriverList.stream().map(companyDriver ->
                CompanyDriverVO.builder()
                        .driverName(companyDriver.getDrivername())
                        .mobile(companyDriver.getMobile())
                        .driverStatus(companyDriver.getDriverstatus())
                        .driverSource(companyDriver.getDriversource())
                        .companyId(companyDriver.getCompanyid())
                        .driverId(companyDriver.getDriverid())
                        .truckId(companyDriver.getTruckid())
                        .build()
        ).collect(Collectors.toList());

        return new PageResult<>(params.getPage(),params.getPerPage(),collect, (int) totalNum);
    }

    /**
     * 查找司机所有关联的企业
     * @param  id 入参
     */
    public List<CompanyDriverVO> getById(Integer id){
        CompanyDriverExample companyDriverExample = new CompanyDriverExample();
        CompanyDriverExample.Criteria criteria = companyDriverExample.createCriteria();
        criteria.andDriveridEqualTo(id);
        Long totalNum = companyDriverMapper.countByExample(companyDriverExample);
        if (totalNum <= Global.ZERO){
            return Collections.emptyList();
        }
        List<CompanyDriver> companyDrivers = companyDriverMapper.selectByExample(companyDriverExample);
        return  companyDrivers.stream().map(companyDriver ->
                CompanyDriverVO.builder()
                    .companyName(companyMapper.selectByPrimaryKey(companyDriver.getCompanyid()).getName())
                    .mobile(companyDriver.getMobile())
                    .truckId(companyDriver.getTruckid())
                    .build()
        ).collect(Collectors.toList());
    }

    /**
     * 查找司机关联的企业
     * @param  driverId 入参
     * @param  companyId 入参
     */
    public List<CompanyDriverVO> getByDriverIdAndCompanyId(Integer driverId, Integer companyId){
        CompanyDriverExample companyDriverExample = new CompanyDriverExample();
        CompanyDriverExample.Criteria criteria = companyDriverExample.createCriteria();

        if(Objects.nonNull(driverId) && driverId > Global.ZERO) {
            criteria.andDriveridEqualTo(driverId);
        }

        if(Objects.nonNull(companyId) && companyId > Global.ZERO) {
            criteria.andCompanyidEqualTo(companyId);
        }

        List<CompanyDriver> companyDrivers = companyDriverMapper.selectByExample(companyDriverExample);

        if(CollectionUtils.isEmpty(companyDrivers)){
            return Collections.emptyList();
        }

        return companyDrivers.stream().map(companyDriver ->
                        CompanyDriverVO.builder()
                                .id(companyDriver.getId())
                                .companyId(companyDriver.getCompanyid())
                                .driverId(companyDriver.getDriverid())
                                .mobile(companyDriver.getMobile())
                                .driverStatus(companyDriver.getDriverstatus())
                                .driverSource(companyDriver.getDriversource())
                                .driverName(companyDriver.getDrivername())
                                .truckId(companyDriver.getTruckid())
                                .build()
                ).collect(Collectors.toList());

    }


    /**
     * 更新中间表
     * @param companyDriverVO 入参
     */
    public void update(CompanyDriverVO companyDriverVO) {
        CompanyDriver companyDriver = new CompanyDriver();
        companyDriver.setMobile(companyDriverVO.getMobile());
        companyDriver.setTruckid(companyDriverVO.getTruckId());
        companyDriver.setDriverid(companyDriverVO.getDriverId());
        companyDriver.setDrivername(companyDriverVO.getDriverName());
        companyDriver.setDriversource(companyDriverVO.getDriverSource());
        companyDriver.setDriverstatus(companyDriverVO.getDriverStatus());
        companyDriver.setLastmodifiedtime(new Date());

        CompanyDriverExample companyDriverExample = new CompanyDriverExample();

         // 当是企业修改 全量更新所有的关系表中的信息
        if(Global.ZERO == companyDriverVO.getCompanyId()){
            companyDriverExample.createCriteria().andDriveridEqualTo(companyDriverVO.getDriverId());
            companyDriverMapper.updateByExampleSelective(companyDriver,companyDriverExample);
            return;
        }

        companyDriver.setCompanyid(companyDriverVO.getCompanyId());
        companyDriverExample.createCriteria().andDriveridEqualTo(companyDriverVO.getDriverId()).andCompanyidEqualTo(companyDriverVO.getCompanyId());

        List<CompanyDriver> companyDrivers = companyDriverMapper.selectByExample(companyDriverExample);
        Optional<CompanyDriver> first = companyDrivers.stream().findFirst();
        if(first.isPresent()){
            CompanyDriver driver = first.get();
            companyDriver.setId(driver.getId());
            companyDriverMapper.updateByPrimaryKeySelective(companyDriver);
            return;
        }
        companyDriverMapper.insert(companyDriver);

    }


    /**
     * 查找司机数量统计
     * @param  companyId 入参
     */
    public DriverStatisticsVO getDriverStatistics(Integer companyId){

        int runNum = getDriverRunNum(companyId);
        int sucNum = getDriverSucNum(companyId);

        return DriverStatisticsVO.builder()
                .usableDriver(sucNum)
                .runDriver(runNum)
                .build();
    }


    public int getDriverSucNum(Integer companyId){
        CompanyDriverExample companyDriverExample = new CompanyDriverExample();
        CompanyDriverExample.Criteria criteria = companyDriverExample.createCriteria();
        criteria.andCompanyidEqualTo(companyId);

        criteria.andDriverstatusEqualTo(DriverStatusEnum.VERIFY_SUCCESS.name());

        long sucNum = companyDriverMapper.countByExample(companyDriverExample);

        return (int)sucNum;

    }

    public int getDriverRunNum(Integer companyId){

        CompanyDriverExample companyDriverExample = new CompanyDriverExample();
        CompanyDriverExample.Criteria criteria = companyDriverExample.createCriteria();
        criteria.andCompanyidEqualTo(companyId);

        List<String> list = new ArrayList<>();
        list.add(DriverStatusEnum.ACTIVATED_WAIT.name());
        list.add(DriverStatusEnum.ACTIVATED_FAIL.name());
        list.add(DriverStatusEnum.APPROVE_ING.name());
        list.add(DriverStatusEnum.APPROVE_FAIL.name());
        list.add(DriverStatusEnum.CONTRACT_ING.name());
        list.add(DriverStatusEnum.CONTRACT_FAIL.name());
        list.add(DriverStatusEnum.BANK_ING.name());
        list.add(DriverStatusEnum.BANK_FAIL.name());
        list.add(DriverStatusEnum.EXISTING_DATA_SHARING.name());
        list.add(DriverStatusEnum.NO_SUBMIT.name());
        criteria.andDriverstatusIn(list);

        long runNum = companyDriverMapper.countByExample(companyDriverExample);

        return (int)runNum;
    }





}
